package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.TaskConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.modular.rest.entity.RestDict;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.AttendAuditStatusEnum;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.EmployeePositionEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.AttendAuditBtyArchivesMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.AttendAuditBtyAreaMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.*;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaAndBtyArchivesResult;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaAuditStatusResult;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaResult;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wjk
 * @since 2021-09-15
 */
@Service
public class AttendAuditBtyAreaServiceImpl extends ServiceImpl<AttendAuditBtyAreaMapper, AttendAuditBtyArea> implements AttendAuditBtyAreaService {

    @Resource
    private AttendAuditBtyArchivesService attendAuditBtyArchivesService;

    @Autowired
    private AttendAuditService attendAuditService;

    @Autowired
    private PushMsgService pushMsgService;

    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @Resource
    private BtyWxMapper btyWxMapper;

    @Resource
    private TaskConfig taskConfig;

    @Resource
    private AttendAuditBtyAreaMapper attendAuditBtyAreaMapper;

    @Resource
    private AttendAuditBtyArchivesMapper attendAuditBtyArchivesMapper;

    @Resource
    private AttendEmployeeMonthService attendEmployeeMonthService;

    @Override
    public void add(AttendAuditBtyAreaParam param){
        AttendAuditBtyArea entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(AttendAuditBtyAreaParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(AttendAuditBtyAreaParam param){
        AttendAuditBtyArea oldEntity = getOldEntity(param);
        AttendAuditBtyArea newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public AttendAuditBtyAreaResult findBySpec(AttendAuditBtyAreaParam param){
        return null;
    }

    @Override
    public List<AttendAuditBtyAreaResult> findListBySpec(AttendAuditBtyAreaParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(AttendAuditBtyAreaParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }
    /**
     * 查询列表，返回人事档案主表，关联各个月考勤记录的查询
     *
     * @author wjk
     * @Date 2021-11-17
     */
    @Override
    public LayuiPageInfo findPageBySpeclistAttendAudit(AttendAuditBtyAreaAuditStatusResult attendAuditBtyAreaAuditStatusResult) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        return LayuiPageFactory.createPageInfo(page);
    }
    /**
     * 查询列表，返回人事档案主表，关联各个月考勤记录的查询,为导出查询，不分页
     *
     * @author wjk
     * @Date 2021-12-01
     */
    @Override
    public List<AttendAuditBtyAreaAuditStatusResult> listAttendAuditForExport(AttendAuditBtyAreaAuditStatusResult attendAuditBtyAreaAuditStatusResult) {
        List<AttendAuditBtyAreaAuditStatusResult> list = this.baseMapper.listAttendAuditForExport(attendAuditBtyAreaAuditStatusResult);
        return list;
    }

    /**
     * 查询列表，返回人事档案主表，关联各个月考勤记录的查询
     *
     * @author wjk
     * @Date 2021-11-17
     */
    @Override
    public Map<String, String> searchSumValue(AttendAuditBtyAreaAuditStatusResult attendAuditBtyAreaAuditStatusResult) {
        Map<String, String> map = new HashMap<String, String>();
        if(ToolUtil.isEmpty(attendAuditBtyAreaAuditStatusResult.getAttendMonth())){
            Map<String,String> mapAttendMonth = this.attendAuditBtyArchivesService.intoAttendEmployeeMonthListValidationParam(null,null);
            String attendMonth = mapAttendMonth.get("attendMonth").replaceAll("-","");
            attendAuditBtyAreaAuditStatusResult.setAttendMonth(attendMonth);
        }

        //统计最新的人事档案中有多少家店，这个数据不跟月份和状态挂钩，这个月只作为参数传值；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(null);
        Page pageContext = getPageContext();
        IPage pageBtyAreaAll = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaAll",String.valueOf(pageBtyAreaAll.getTotal()));

        //统计这个月已经多少家店完成了考勤；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.SUBMIT_THROUGH.getCode());
        IPage pageSubmitThrough = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaSubmitThrough",String.valueOf(pageSubmitThrough.getTotal()));

        //统计这个月已经多少家店考勤被驳回；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.SUBMIT_BACK.getCode());
        IPage pageSubmitBack = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaSubmitBack",String.valueOf(pageSubmitBack.getTotal()));

        //统计这个月已经多少家店考勤提交未审核；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.SUBMIT_AUDIT.getCode());
        IPage pageSubmitAudit = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaSubmitAudit",String.valueOf(pageSubmitAudit.getTotal()));

        //统计这个月已经多少家店考勤未提交；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.NOT_SUBMIT.getCode());
        IPage pageNotSubmit = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaNotSubmit",String.valueOf(pageNotSubmit.getTotal()));

        //统计这个月已经多少家店未创建考勤；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.NOT_CREATE.getCode());
        IPage pageNotCreate = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaNotCreate",String.valueOf(pageNotCreate.getTotal()));

        //统计这个月已经多少家店未创建考勤；
        attendAuditBtyAreaAuditStatusResult.setAuditStatus(AttendAuditStatusEnum.NOT_KQDZ.getCode());
        IPage pageNotKqdz = this.baseMapper.customPageListAttendAudit(pageContext, attendAuditBtyAreaAuditStatusResult);
        map.put("BtyAreaNotKqdz",String.valueOf(pageNotKqdz.getTotal()));

        //统计这个月已经多少家店未完成考勤；
        //未创建+未提交+待审核+被驳回的
        int btyAreaNotThrough = Integer.parseInt(map.get("BtyAreaNotCreate"))+Integer.parseInt(map.get("BtyAreaNotSubmit"))+Integer.parseInt(map.get("BtyAreaSubmitAudit"))+Integer.parseInt(map.get("BtyAreaSubmitBack"));
        map.put("BtyAreaNotThrough",String.valueOf(btyAreaNotThrough));
        //考勤月份
        StringBuffer sb = new StringBuffer(attendAuditBtyAreaAuditStatusResult.getAttendMonth());
        sb.insert(4, "-");
        map.put("BtyAreaAttendMonth",sb.toString());

        return map;
    }



    /**
     * 根据营运经理的名字,和店名模糊匹配获取营运经理下的店的列表;
     *
     * @author wjk
     * @Date 2021-10-19
     */

    @Override
    public List<AttendAuditBtyArea> getShowListByYyjlName(String yyjlName,String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getYyjl,yyjlName);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }



    /**
     * 根据督导的名字,和店名模糊匹配获取督导下的店的列表;
     *
     * @author wjk
     * @Date 2021-09-15
     */

    @Override
    public List<AttendAuditBtyArea> getShowListByDdName(String ddName,String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getDd,ddName);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        List<AttendAuditBtyArea> list = this.list(queryWrapper);
        return list;

    }
    /**
     * 根据督导的名字,和店名模糊匹配获取督导下的店的列表-分页;
     *
     * @author wjk
     * @Date 2021-11-19
     */
    @Override
    public IPage<AttendAuditBtyArea> getShowListByDdNameLayuiPage(Page pageContext, String userName, String shopName){
        IPage<AttendAuditBtyArea> page = this.baseMapper.getShowListByDdNameLayuiPage(pageContext,userName,shopName);
        return page;
    }
    /**
     * 若督导列表查询不到数据则查询大店长下的店铺，返回相应的数据
     * @Date 2021-11-19
     */
    @Override
    public IPage<AttendAuditBtyArea> getShowListByDdzNameLayuiPage(Page pageContext, String userName, String shopName){
        IPage<AttendAuditBtyArea> page = this.baseMapper.getShowListByDdzNameLayuiPage(pageContext,userName,shopName);
        return page;
    }
    /**
     * 根据大店长的名字,和店名模糊匹配获取大店长下的店的列表;
     *
     * @author wjk
     * @Date 2021-10-19
     */

    @Override
    public List<AttendAuditBtyArea> getShowListByDdzName(String ddzName,String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getXm,ddzName);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }

    /**
     * 根据考勤店长的名字,和店名模糊匹配获取考勤店长下的店的列表;
     *
     * @author wjk
     * @Date 2021-10-19
     */

    @Override
    public List<AttendAuditBtyArea> getShowListByKqDzName(String kqDzName,String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getKqDz,kqDzName);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }
    /**
     * 根据店名匹配获取店的信息;
     *
     * @author wjk
     * @Date 2021-11-05
     */
    @Override
    public AttendAuditBtyArea getShopInfoByDm(String shopName){
        AttendAuditBtyArea attendAuditBtyArea = new AttendAuditBtyArea();
        if(ToolUtil.isEmpty(shopName)){
             return attendAuditBtyArea;
        }
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getDm,shopName);
        List<AttendAuditBtyArea> list =  this.list(queryWrapper);
        if(list.size()>0){
            attendAuditBtyArea= list.get(0);
        }
        return attendAuditBtyArea;
    }
    /**
     * 根据考勤店长的手机号获取妖码
     * @param account
     * @author wjk
     * @Date 2021-11-12
     */
    @Override
    public Map<String, String> queryYaoMa(String account) {
        AttendAuditBtyArea attendAuditBtyArea = new AttendAuditBtyArea();
        attendAuditBtyArea.setKqDh(account);
        Map<String, String> map = this.baseMapper.queryYaoMa(attendAuditBtyArea);
        if(ToolUtil.isNotEmpty(map)){
            return map;
        }else {
            map = new HashMap<String, String>();
            map.put("dm","");
            map.put("ym","");
        }

        return map;
    }


    /**
     * 根据员工信息，督导手机号，设置店长；
     * @author wjk
     * @Date 2021-09-15
     */
    @Override
    public Map<String, String> setEmployeeToDz(AttendAuditBtyArchivesParam attendAuditBtyArchivesParam, String account) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("flag","false");
        map.put("message","");

        //获取员工
        AttendAuditBtyArchives attendAuditBtyArchives = attendAuditBtyArchivesService.detailById(attendAuditBtyArchivesParam);

        //未获取到员工，则不需要任何处理任何的信息，返回失败
        if(ToolUtil.isEmpty(attendAuditBtyArchives)||ToolUtil.isEmpty(attendAuditBtyArchives.getId())||ToolUtil.isEmpty(attendAuditBtyArchives.getTel())){
            map.put("message","未获取到员工信息，请核实员工资料还在人事档案中。");
            return map;
        }
        //员工手机号必须合法，是11位，则可以设置这个人为店长
        if (attendAuditBtyArchives.getTel().length() != 11){
            map.put("message","员工档案信息中，手机号必须是正确的，才可指定该员工为考勤店长，请联系人事修改该员工手机号。");
            return map;

        }
        //未获取到督导，或者大店长的信息，则返回失败的情况
        AttendAuditBtyArchives attendAuditBtyArchivesdd = attendAuditBtyArchivesService.getOneByPhone(account);
        if(ToolUtil.isEmpty(attendAuditBtyArchivesdd.getId())){
            map.put("message","未获取到当前登录人的权限，请当前登录资料是否在人事档案中，或者登录账号与人事中手机号是否一致。");
            return map;
        }

        //查询当前日期是否在考勤期间，
        Map<String,String> mapAttendDay = this.attendAuditService.getCreateAttendButton();
        //在考勤期间，则进行判断，若该店有店长了，则不进行修改店长电话
        if("0".equals(mapAttendDay.get("buttonValid"))){
            //根据店名获取到该店考勤店长电话不为空，
            AttendAuditBtyArea attendAuditBtyAreaOld = getShopInfoByDm(attendAuditBtyArchives.getDm());
            if(ToolUtil.isNotEmpty(attendAuditBtyAreaOld)&&ToolUtil.isNotEmpty(attendAuditBtyAreaOld.getKqDh())){
                map.put("message","考勤期间不允许进行修改店长。");
                return map;
            }
        }

        // 此处根据督导，或者大店长的手机号，和店名，证明是督导，或者大店长之后才可以进行信息进行修改；
        Map<String,String>  mapZw = attendAuditBtyArchivesService.commonGetEmplistPermissionsOnlyddDdz(account,attendAuditBtyArchives.getDm());
        //若没有权限,则直接返回空
        if("false".equals(mapZw.get("success"))){
            map.put("message","未获取到当前登录人的权限，请确定人事档案中的门店是否在您的管辖范围之内。");
            return map;
        }
        //验证，督导，或者大店长权限，才可以进行修改
        if(mapZw.get("zw").equals(EmployeePositionEnum.POSITION21.getMsg())||mapZw.get("zw").equals(EmployeePositionEnum.POSITION22.getMsg())){
            //根据电话，查询这个是不是已经在其他店作为店长，
            AttendAuditBtyArea attendAuditBtyAreaOld = getShopInfoByDzPhone(attendAuditBtyArchives.getTel());

            String message = "";
            if(ToolUtil.isNotEmpty(attendAuditBtyAreaOld)&&ToolUtil.isNotEmpty(attendAuditBtyAreaOld.getDm())){
                if(!attendAuditBtyAreaOld.getDm().equals(attendAuditBtyArchivesParam.getDm())) {
                   // map.put("message", "该员工已在[" + attendAuditBtyAreaOld.getDm() + "]出任考勤店长一职,不可一人担任多家店的考勤店长。");
                   // return map;
                    message = "请去指定[" + attendAuditBtyAreaOld.getDm() + "]的店长。";
                    //将原来店的店长数据清空
                    this.baseMapper.setEmployeeToDzIsNull(attendAuditBtyAreaOld);
                }
            }

            AttendAuditBtyArea attendAuditBtyArea = new AttendAuditBtyArea();
            //查询条件
            attendAuditBtyArea.setDm(attendAuditBtyArchives.getDm());

            //设置的店长名字和电话
            attendAuditBtyArea.setKqDz(attendAuditBtyArchives.getXm());
            attendAuditBtyArea.setKqDh(attendAuditBtyArchives.getTel());

            //督导设置店长
            boolean ddSetDz =  this.baseMapper.setEmployeeToDz(attendAuditBtyArea);
            if(ddSetDz){
                map.put("flag","true");
                map.put("message","指定店长成功。"+message);
                //推送督导设置的店长到店长手机号账号下的小妖app
                pushMsgService.attendAuditSetDzPushMsgToIM(attendAuditBtyArchives.getDm(),attendAuditBtyArchives.getTel(),attendAuditBtyArchives.getXm(),attendAuditBtyArchivesdd.getXm());
                //推送督导设置的店长到店长手机号的微信账号信息
                setEmployeeToDzToWeChat(attendAuditBtyArchives.getDm(),attendAuditBtyArchives.getTel(),attendAuditBtyArchives.getXm(),attendAuditBtyArchivesdd.getXm());
                return map;

            }else{
                map.put("flag","false");
                map.put("message","验证店名和店长信息失败。");
                return map;
            }


            //将员工设置为店长
            //此处因为 此店长只用作做考勤记录，故不进行店内员工职位的变动,此处将不进行修改员工表数据，不进行数据的处理
            //attendAuditBtyArchives.setZw(RoleIdEnum.ROLE_STORE_MANAGER.getMessage());
            //boolean empSetDz = this.attendAuditBtyArchivesService.setEmployeeToDz(attendAuditBtyArchives);
        }
        map.put("message","权限不足。");
        return map;
    }

    /**
     * 将督导(或大店长)指定店长之后，推送店长
     * @author wjk
     * @Date 2021-11-10
     */
     private void  setEmployeeToDzToWeChat(String shopName, String dzMobile,String kqDz,String ddXm){
         //当前时间
         String now = DateUtil.getNow();
         //修改店长公众号推送提醒：“xxx”您好，“xxx”已指定您为“上海崇明万达店”的店长，请在每月月底最后一天，和下月初的1号、2号做本店考勤，进入小妖APP，点击录入考勤菜单可进行考勤录入
          String data ="\""+kqDz+"\" 您好，\""+ddXm+"\"已指定您为\"" + shopName+"\"的店长，请在每月月底最后一天，和下月初的1号、2号做本店考勤，进入小妖APP，点击录入考勤菜单可进行考勤录入";
         JSONObject tempObj = weChatSendTempMsgService.setTempParam(shopName, null, "考勤提醒", "考勤提醒", now, data);

         if ("y".equals(taskConfig.getRun())) {

         } else {
             dzMobile = "17686420611";
         }
         //获取受让方openid
         User user = btyWxMapper.getOpenId(dzMobile);
         String[] openid = null;
         if (ToolUtil.isNotEmpty(user)) {
             openid = new String[]{user.getOpenid()};
         }

         weChatSendTempMsgService.sendmsg(openid, null, tempObj);
     }

    /**
     * 根据店长的手机号码，店长旗下店的信息；
     * @author wjk
     * @Date 2021-09-16
     */
    @Override
    public AttendAuditBtyArea getShopInfoByDzPhone(String account) {

        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getKqDh,account);

        List<AttendAuditBtyArea> list = this.list(queryWrapper);
        AttendAuditBtyArea attendAuditBtyArea = new AttendAuditBtyArea();
        if(list.size() > 0){
            attendAuditBtyArea = list.get(0);
        }
        return attendAuditBtyArea;
    }

    private Serializable getKey(AttendAuditBtyAreaParam param){
        return null;
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private AttendAuditBtyArea getOldEntity(AttendAuditBtyAreaParam param) {
        return this.getById(getKey(param));
    }

    private AttendAuditBtyArea getEntity(AttendAuditBtyAreaParam param) {
        AttendAuditBtyArea entity = new AttendAuditBtyArea();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    /**
     * 查询营运经理的列表，
     *
     * @author wjk
     * @Date 2021-12-01
     */
    @Override
    public List<AttendAuditBtyArea> getYyjlList() {
        return this.baseMapper.getYyjlList();
    }

    @Override
    public void updateDh(String dhTels,String dh){
        //人事架构表中查找是否有符合的手机号
        List<AttendAuditBtyArea> attendAuditBtyAreaList=new LambdaQueryChainWrapper<>(attendAuditBtyAreaMapper)
                .eq(AttendAuditBtyArea::getDh,dhTels)
                .list();
        //根据已查到的手机号匹配人事架构表手机号 匹配到先更新保存原手机号，然后替换新手机号
        attendAuditBtyAreaList.forEach(i -> {
            if (!i.getDh().equals(dh)) {
                LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AttendAuditBtyArea::getDh,dh);
                AttendAuditBtyArea attendAuditBtyAreaSOne = attendAuditBtyAreaMapper.selectOne(queryWrapper);
                if(attendAuditBtyAreaSOne==null){
                    i.setDhTels(dhTels);
                    i.setDh(dh);
                    //引入人事架构表数据操作层
                    attendAuditBtyAreaMapper.updateById(i);
                }
            }
        });
    }

    @Override
    public void updateKqDh(String kqDhTels,String kqDh){
        //人事架构表中查找是否有符合的手机号
        List<AttendAuditBtyArea> attendAuditBtyAreaList=new LambdaQueryChainWrapper<>(attendAuditBtyAreaMapper)
                .eq(AttendAuditBtyArea::getKqDh,kqDhTels)
                .list();
        //根据已查到的手机号匹配人事架构表手机号 匹配到先更新保存原手机号，然后替换新手机号
        attendAuditBtyAreaList.forEach(i -> {
            if (!i.getKqDh().equals(kqDh)) {
                LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AttendAuditBtyArea::getKqDh,kqDh);
                AttendAuditBtyArea attendAuditBtyAreaSOne = attendAuditBtyAreaMapper.selectOne(queryWrapper);
                if(attendAuditBtyAreaSOne==null){
                    i.setKqDhTels(kqDhTels);
                    i.setKqDh(kqDh);
                    //引入人事架构表数据操作层
                    attendAuditBtyAreaMapper.updateById(i);
                }
            }
        });
    }



    @Override
    public void updateYydhTels(String yydhTels,String yydh){
        //人事架构表中查找是否有符合的手机号
        List<AttendAuditBtyArea> attendAuditBtyAreaList=new LambdaQueryChainWrapper<>(attendAuditBtyAreaMapper)
                .eq(AttendAuditBtyArea::getYydh,yydhTels)
                .list();
        //根据已查到的手机号匹配人事架构表手机号 匹配到先更新保存原手机号，然后替换新手机号
        attendAuditBtyAreaList.forEach(i -> {
            if (!i.getYydh().equals(yydh)) {
                LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AttendAuditBtyArea::getYydh,yydh);
                AttendAuditBtyArea attendAuditBtyAreaSOne = attendAuditBtyAreaMapper.selectOne(queryWrapper);
                if(attendAuditBtyAreaSOne==null){
                    i.setYydhTels(yydhTels);
                    i.setYydh(yydh);
                    //引入人事架构表数据操作层
                    attendAuditBtyAreaMapper.updateById(i);
                }
            }
        });
    }

    @Override
    public void updateDddhTels(String dddhTels,String dddh){
        //人事架构表中查找是否有符合的手机号
        List<AttendAuditBtyArea> attendAuditBtyAreaList=new LambdaQueryChainWrapper<>(attendAuditBtyAreaMapper)
                .eq(AttendAuditBtyArea::getDddh,dddhTels)
                .list();
        //根据已查到的手机号匹配人事架构表手机号 匹配到先更新保存原手机号，然后替换新手机号
        attendAuditBtyAreaList.forEach(i -> {
            if (!i.getDddh().equals(dddh)) {
                LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AttendAuditBtyArea::getDddh,dddh);
                AttendAuditBtyArea attendAuditBtyAreaSOne = attendAuditBtyAreaMapper.selectOne(queryWrapper);
                if(attendAuditBtyAreaSOne==null){
                    i.setDddhTels(dddhTels);
                    i.setDddh(dddh);
                    //引入人事架构表数据操作层
                    attendAuditBtyAreaMapper.updateById(i);
                }
            }
        });
    }


    @Override
    public void updateArchivesTel(String oldTels,String tel){
        //引入人事档案表数据操作层
        List<Long> attendAuditBtyAreaList=attendAuditBtyArchivesMapper.archivesIdList(oldTels);
        for (Long archivesId:attendAuditBtyAreaList) {
            if(!oldTels.equals(tel)){
                List<Long> attendAuditBtyArea=attendAuditBtyArchivesMapper.archivesIdList(tel);
                if(attendAuditBtyArea==null||attendAuditBtyArea.size()==0){
                    attendAuditBtyArchivesMapper.updateArchivesTel(oldTels,tel,archivesId);
                }
            }
        }
    }

    /**
     * 查询列表，返回人事列表中的店，或者人员的一些影响的一些信息
     *
     * @author wjk
     * @Date 2021-12-23
     * @param attendAuditBtyAreaAndBtyArchivesParam
     * @return
     */
    @Override
    public LayuiPageInfo pagelistAttendAuditForImpact(AttendAuditBtyAreaAndBtyArchivesParam attendAuditBtyAreaAndBtyArchivesParam) {
        Page pageContext = getPageContext();
        String allImpact = "100";
        String shopImpact = "101,102";
        String empImpact = "103,104,105,106,107,108,109,110,111";
        // 若是查询全部情况
        if(allImpact.equals(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())){
            IPage page = this.baseMapper.pagelistAttendAuditForImpact(pageContext, attendAuditBtyAreaAndBtyArchivesParam);
            return LayuiPageFactory.createPageInfo(page);
        }
        // 若是查询情况1和情况2
        if(shopImpact.indexOf(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())>-1){
            IPage page = this.baseMapper.pagelistAttendAuditForImpactShop(pageContext, attendAuditBtyAreaAndBtyArchivesParam);
            return LayuiPageFactory.createPageInfo(page);
        }
        // 若是查询情况3,4,5,6,7,8,9,10,11
        if(empImpact.indexOf(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())>-1){
            IPage page = this.baseMapper.pagelistAttendAuditForImpactEmp(pageContext, attendAuditBtyAreaAndBtyArchivesParam);
            return LayuiPageFactory.createPageInfo(page);
        }

        return new LayuiPageInfo();
    }

    /**
     * 查询列表，返回人事列表中的店，或者人员的一些影响正常考勤的一些信息，不分页
     *
     * @param attendAuditBtyAreaAndBtyArchivesParam
     * @return
     */
    @Override
    public List<AttendAuditBtyAreaAndBtyArchivesResult> listAttendAuditForImpactForExport(AttendAuditBtyAreaAndBtyArchivesParam attendAuditBtyAreaAndBtyArchivesParam) {
        String allImpact = "100";
        String shopImpact = "101,102";
        String empImpact = "103,104,105,106,107,108,109,110,111";
        // 若是查询全部情况
        if(allImpact.equals(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())){
            List<AttendAuditBtyAreaAndBtyArchivesResult> list = this.baseMapper.listAttendAuditForImpact(attendAuditBtyAreaAndBtyArchivesParam);
            return list;
        }

        // 若是查询情况1和情况2
        if(shopImpact.indexOf(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())>-1){
            List<AttendAuditBtyAreaAndBtyArchivesResult> list = this.baseMapper.listAttendAuditForImpactShop(attendAuditBtyAreaAndBtyArchivesParam);
            return list;
        }

        // 若是查询情况3,4,5,6,7,8,9,10,11
        if(empImpact.indexOf(attendAuditBtyAreaAndBtyArchivesParam.getImpactType())>-1){
            List<AttendAuditBtyAreaAndBtyArchivesResult> list = this.baseMapper.listAttendAuditForImpactEmp(attendAuditBtyAreaAndBtyArchivesParam);
            return list;
        }

        return new ArrayList<AttendAuditBtyAreaAndBtyArchivesResult>();
    }


    /**
     * 查询列表，统计一些影响正常考勤的一些信息，
     *
     * @author wjk
     * @Date 2021-12-27
     */
    @Override
    public Map<String, String> searchSumValueImpact() {
        Map<String, String> map = new HashMap<String, String>();
        AttendAuditBtyAreaAndBtyArchivesParam param = new AttendAuditBtyAreaAndBtyArchivesParam();


//    <div id="noDz">情况1：未指定店长，无法进行创建考勤，和做考勤</div>
//    <div id="dzNotInDm">情况2：考勤店长不在本店，考勤店长无法跨店进行考勤</div>
//
//    <div id="sfzHaveTwo">情况3：身份证重复，两条数据可能是一个人，考勤被做双份</div>
//    <div id="telHaveTwo">情况4：手机号重复，两条数据可能是一个人，考勤被做双份</div>
//    <div id="yhkHaveTwo">情况5：银行卡重复，两个人有可能造成工资错误发放</div>
//
//    <div id="zwNotInZw">情况6：职位异常，职位不在('营运经理', '督导', '大店长', '店长', '储备', '店助', '管培生', '后厨员工', '迎宾', '前厅员工', '员工', '兼职', '钟点工')职位之中</div>
//    <div id="zwZSGzGwNotHundred ">情况7：正式员工，工资非整百</div>
//    <div id="zwJzZdgGwNotZero">情况8：兼职，钟点工，的岗位工资不为0的情况</div>
//    <div id="zwJzNotHava">情况9：兼职工资超过500元/人天</div>
//    <div id="zwZdgNotHava">情况10：钟点工超过50元/人小时</div>
//
//    <div id="ddYyjlZtOne">情况11：营运经理，督导，不发工资情况</div>


        //全部
        param.setImpactType("100");
        List<AttendAuditBtyAreaAndBtyArchivesResult> allImpact = this.baseMapper.listAttendAuditForImpact(param);
        map.put("allImpact", String.valueOf(allImpact.size()));


        //情况1：未指定店长，无法进行创建考勤，和做考勤
        param.setImpactType("101");
        List<AttendAuditBtyAreaAndBtyArchivesResult> noDz = this.baseMapper.listAttendAuditForImpactShop(param);
        map.put("noDz", String.valueOf(noDz.size()));


        //情况2：考勤店长不在本店，考勤店长无法跨店进行考勤
        param.setImpactType("102");
        List<AttendAuditBtyAreaAndBtyArchivesResult> dzNotInDm = this.baseMapper.listAttendAuditForImpactShop(param);
        map.put("dzNotInDm", String.valueOf(dzNotInDm.size()));





        //情况3：身份证重复，两条数据可能是一个人，考勤被做双份
        param.setImpactType("103");
        List<AttendAuditBtyAreaAndBtyArchivesResult> sfzHaveTwo = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("sfzHaveTwo", String.valueOf(sfzHaveTwo.size()));


        //情况4：手机号重复，两条数据可能是一个人，考勤被做双份
        param.setImpactType("104");
        List<AttendAuditBtyAreaAndBtyArchivesResult> telHaveTwo = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("telHaveTwo", String.valueOf(telHaveTwo.size()));

        //情况5：银行卡重复，两个人有可能造成工资错误发放
        param.setImpactType("105");
        List<AttendAuditBtyAreaAndBtyArchivesResult> yhkHaveTwo = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("yhkHaveTwo", String.valueOf(yhkHaveTwo.size()));


        //情况6：职位异常，职位不在('营运经理', '督导', '大店长', '店长', '储备', '店助', '管培生', '后厨员工', '迎宾', '前厅员工', '员工', '兼职', '钟点工')职位之中
        param.setImpactType("106");
        List<AttendAuditBtyAreaAndBtyArchivesResult> zwNotInZw = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("zwNotInZw", String.valueOf(zwNotInZw.size()));


        //情况7：正式员工，工资非整百
        param.setImpactType("107");
        List<AttendAuditBtyAreaAndBtyArchivesResult> zwZSGzGwNotHundred = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("zwZSGzGwNotHundred", String.valueOf(zwZSGzGwNotHundred.size()));

        //情况8：兼职，钟点工，的岗位工资不为0的情况
        param.setImpactType("108");
        List<AttendAuditBtyAreaAndBtyArchivesResult> zwJzZdgGwNotZero = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("zwJzZdgGwNotZero", String.valueOf(zwJzZdgGwNotZero.size()));


        //情况9：兼职工资超过500元/人天
        param.setImpactType("109");
        List<AttendAuditBtyAreaAndBtyArchivesResult> zwJzNotHava = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("zwJzNotHava", String.valueOf(zwJzNotHava.size()));

        //情况10：钟点工超过50元/人小时
        param.setImpactType("110");
        List<AttendAuditBtyAreaAndBtyArchivesResult> zwZdgNotHava = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("zwZdgNotHava", String.valueOf(zwZdgNotHava.size()));


        //情况11：营运经理，督导，不发工资情况
        param.setImpactType("111");
        List<AttendAuditBtyAreaAndBtyArchivesResult> ddYyjlZtOne = this.baseMapper.listAttendAuditForImpactEmp(param);
        map.put("ddYyjlZtOne", String.valueOf(ddYyjlZtOne.size()));

        return map;
    }


    /**
     *  查询非考勤期间， 设置的考勤店长不在设置的店内，店长被调走情况，将该店的考勤店长，考勤店长电话清除
     * @author wjk
     * @Date 2021-12-29
     * @return map
     */
    @Override
    public Map<String,String> queryDzNotInDm(){
        Map<String,String> map = new HashMap<String,String>();

        AttendAuditBtyAreaAndBtyArchivesParam param = new AttendAuditBtyAreaAndBtyArchivesParam();

        //情况2：考勤店长不在本店，考勤店长无法跨店进行考勤
        param.setImpactType("102");
        List<AttendAuditBtyAreaAndBtyArchivesResult> dzNotInDm = this.baseMapper.listAttendAuditForImpactShop(param);
        map.put("dzNotInDm", String.valueOf(dzNotInDm.size()));

        Map<String,String> mapCreateAttendButton = this.attendAuditService.getCreateAttendButton();
        //非考勤期间，清理这些数据
        if(!"0".equals(mapCreateAttendButton.get("buttonValid"))){
            //查询相应的信息清空这些店的考勤店长
            if(dzNotInDm.size()>0){
                for(int i = 0 ;i<dzNotInDm.size();i++){
                    AttendAuditBtyAreaAndBtyArchivesResult result=  dzNotInDm.get(i);
                    //根据店表的id ,清除该店的考勤店长的店的信息
                    AttendAuditBtyArea attendAuditBtyArea = new AttendAuditBtyArea();
                    attendAuditBtyArea.setId(result.getId());
                    Boolean flag = this.baseMapper.setEmployeeToDzIsNull(attendAuditBtyArea);
                }
                map.put("msg", "清理考勤店长档案不本店的情况"+dzNotInDm.size()+"条，请联系督导重新指定店长。");
            }else{
                map.put("msg", "未查询到考勤店长，档案不本店的情况，无需进行清理。");
            }
        }else{
            map.put("msg", "考勤期间，不允许清除店长信息。");
        }


        return map;
    }


    /**
     * 获取需要同步那个月的考勤信息
     * @author wjk
     * @Date 2022-02-21
     */
    @Override
    public Map<String, String> getSynchronousMonth() {
        Map<String, String> map = new HashMap<String,String>();
        map.put("synchronousMonth","未在字典中设置同步考勤月份的时间,请联系系统管理员配置");
        map.put("flag","false");
        List<RestDict> list = this.baseMapper.getSynchronousMonth();
        if(list.size()>0){
            RestDict sysDict = list.get(0);
            if(ObjectUtil.isNotEmpty(sysDict)&&ObjectUtil.isNotEmpty(sysDict.getCode())){
                map.put("synchronousMonth",sysDict.getCode());
                map.put("flag","true");
            }
        }
        return map;
    }

    /**
     * 月度考勤同步回人事档案
     * @author wjk
     * @Date 2022-02-21
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> synchronousAttendEmployeeMonth(AttendEmployeeMonthSynchronousParam param) throws ParseException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("flag","false");
        map.put("message","");

        //验证前端传回的月数,是否和后端配置一致
        Map<String, String> synchronousMonthMap = getSynchronousMonth();
        if(synchronousMonthMap.get("flag").equals("false")){
            map.put("flag","false");
            map.put("message", map.get("synchronousMonth"));
            return map;
        }

        if(synchronousMonthMap.get("flag").equals("true")){
            if(!synchronousMonthMap.get("synchronousMonth").equals(param.getSynchronousMonth())){
                map.put("flag","false");
                map.put("message", "同步月份不正确,请确认是否应该同步["+param.getSynchronousMonth()+"]月的数据。");
                return map;
            }
        }

        //判断这个月是否有数据
        AttendAuditBtyAreaAuditStatusResult resultParam = new AttendAuditBtyAreaAuditStatusResult();
        resultParam.setAttendMonth(param.getSynchronousMonth());
        Map<String, String> searchSumValueMap = searchSumValue(resultParam);
        String BtyAreaSubmitThrough  =  searchSumValueMap.get("BtyAreaSubmitThrough");
        if("0".equals(BtyAreaSubmitThrough)){
            map.put("flag","false");
            map.put("message", "本月提交通过数据为0,请确认,是否应该同步本月数据。");
            return map;
        }

        //查询这个月未完成考勤的店铺
        String BtyAreaNotThrough  =  searchSumValueMap.get("BtyAreaNotThrough");

        //对比前台传回的数量是否一致
        if(!param.getNotSynchronousshopNum().equals(BtyAreaNotThrough)){
            map.put("flag","false");
            map.put("message", "未审核通过的店铺为"+BtyAreaNotThrough+"家,无需做考勤的店铺为"+param.getNotSynchronousshopNum()+"家，店铺数量不匹配，请确认后再进行同步。");
            return map;
        }

        //同步本月的考勤信息
        AttendAuditDdSupervisorParam employeeMonthParam = new AttendAuditDdSupervisorParam();
        employeeMonthParam.setAttendMonth(param.getSynchronousMonth());
        Map<String,String> mapSynchronous = this.attendEmployeeMonthService.synchronousAttendEmployeeMonthToBtyArchives(employeeMonthParam);
        if(String.valueOf(mapSynchronous.get("flag")).equals("false")){
            map.put("flag","false");
            map.put("message",mapSynchronous.get("message"));
            return map;
        }

        //修改字典表中的同步月份,加一月,修改
        String monthLastStr = synchronousMonthMap.get("synchronousMonth")+"01 00:00:00";

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date monthLast = sdf.parse(monthLastStr);
        Date monthNew = attendEmployeeMonthService.calculateMonth(monthLast,1);
        SimpleDateFormat sdfyyyyMM = new SimpleDateFormat("yyyyMM");
        String monthNewStr = sdfyyyyMM.format(monthNew);
        Boolean falg = updateSynchronousMonth(monthNewStr);
        if(falg){
            map.put("flag","true");
            map.put("message","同步成功。");
            return map;
        }
        map.put("flag","true");
        map.put("message","同步失败，未满足同步条件。");
        return map;
    }

    // 更新字典表中的同步月份信息
    private Boolean updateSynchronousMonth(String month) {
        return this.baseMapper.updateSynchronousMonth(month);
    }







    /*************** 2021-02-10 绩效使用*****************/


    /**
     * 根据电话号码获取在架构中的职位
     *
     * @author wjk
     * @Date 2021-02-10
     */
    @Override
    public String getBtyAreaZwByTel(String tel) {

        String zwStr = "";

        List<AttendAuditBtyArea> listYyjl = getShowListByYyjlTel(tel,null);
        if(listYyjl.size()>0) {
            zwStr = "营运经理";
        }
        List<AttendAuditBtyArea> listDd = getShowListByDdTel(tel,null);
        if(listDd.size()>0) {
            if(ToolUtil.isNotEmpty(zwStr)){
                zwStr = zwStr+"，督导";
            }else{
                zwStr = "督导";
            }

        }
        List<AttendAuditBtyArea> listDdz = getShowListByDdzTel(tel,null);
        if(listDdz.size()>0) {
            if(ToolUtil.isNotEmpty(zwStr)){
                zwStr = zwStr+"，大店长";
            }else{
                zwStr = "大店长";
            }

        }
        List<AttendAuditBtyArea> listDz = getShowListByKqDzTel(tel,null);
        if(listDz.size()>0) {
            if(ToolUtil.isNotEmpty(zwStr)){
                zwStr = zwStr+"，店长";
            }else{
                zwStr = "店长";
            }
        }
        return zwStr;
    }


    /**
     * 根据运营经理的电话,和店名模糊匹配获取运营经理的店的列表;
     *
     * @author wjk
     * @Date 2021-02-10
     */
    @Override
    public List<AttendAuditBtyArea> getShowListByYyjlTel(String tel, String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getYydh,tel);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }

    /**
     * 根据督导的电话,和店名模糊匹配获取督导下的店的列表;
     *
     * @author wjk
     * @Date 2021-02-10
     */
    @Override
    public List<AttendAuditBtyArea> getShowListByDdTel(String tel, String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getDddh,tel);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }

    /**
     * 根据大店长的电话,和店名模糊匹配获取大店长下的店的列表;
     *
     * @author wjk
     * @Date 2021-02-10
     */
    @Override
    public List<AttendAuditBtyArea> getShowListByDdzTel(String tel, String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getDh,tel);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }

    /**
     * 根据考勤店长的电话,和店名模糊匹配获取考勤店长下的店的列表;
     *
     * @author wjk
     * @Date 2021-02-10
     */
    @Override
    public List<AttendAuditBtyArea> getShowListByKqDzTel(String tel, String shopName) {
        LambdaQueryWrapper<AttendAuditBtyArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendAuditBtyArea::getKqDh,tel);
        if(ToolUtil.isNotEmpty(shopName)){
            queryWrapper.like(AttendAuditBtyArea::getDm,shopName);
        }
        return this.list(queryWrapper);
    }


//    /**
//     * 查询列表，返回人事列表中的店，或者人员的一些影响正常考勤的一些信息
//     * 查询缺少考勤店长的情况
//     *
//     * @author wjk
//     * @Date 2021-12-23
//     */
//
//    @Override
//    public LayuiPageInfo listAttendAuditForImpactNoDz(AttendAuditBtyAreaAuditStatusResult attendAuditBtyAreaAuditStatusResult) {
//        Page pageContext = getPageContext();
//        IPage page = this.baseMapper.listAttendAuditForImpactNoDz(pageContext, attendAuditBtyAreaAuditStatusResult);
//        return LayuiPageFactory.createPageInfo(page);
//    }
}
